//
//  DCCycleScrollViewCell.m
//  DCCycleScrollView
//
//  Created by cheyr on 2018/2/27.
//  Copyright © 2018年 cheyr. All rights reserved.
//

#import "DCCycleScrollViewCell.h"
#import <AVFoundation/AVFoundation.h>
#import "HomeBannerModel.h"
#import <SDWebImage/UIImage+GIF.h>
@interface DCCycleScrollViewCell()
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) id timeObserve;
@property (nonatomic, strong) UIButton *nameClick;
@property (nonatomic, assign) BOOL isPlaying;
/*
 * 播放进度
 */
@property (nonatomic, assign) float progress;
/*
 * 当前播放时间(00:00)
 */
@property (nonatomic, copy) NSString * timeNow;
/*
 * 总时长(00:00)
 */
@property (nonatomic, copy) NSString * duration;
/*
 * 当前播放时间(秒)
 */
@property (nonatomic, copy) NSString * playTime;
/*
 * 总时长(秒)
 */
@property (nonatomic, copy) NSString * playDuration;

@end

@implementation DCCycleScrollViewCell

//@property (nonatomic, strong)UIView*      labelMaskView;
//@property (nonatomic, strong)UILabel*     label;

-(instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        [self.contentView addSubview:self.imageView];
        [self.contentView addSubview:self.labelMaskView];
        [self.contentView addSubview:self.label];
        [self.contentView addSubview:self.playBGView];
        [self.playBGView addSubview:self.playBtn];
        [self.contentView addSubview:self.proBGView];
        [self.contentView addSubview:self.nameClick];
        

        

    }
    return self;
}
-(void)layoutSubviews
{
    self.imageView.frame = self.bounds;

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.imageView.bounds cornerRadius:self.imgCornerRadius];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer.frame = self.bounds;
    //设置图形样子
    maskLayer.path = maskPath.CGPath;
    _imageView.layer.mask = maskLayer;
    [_label sizeToFit];
    _label.frame=CGRectMake(self.bounds.size.width-_label.frame.size.width-wid(20),0,_label.frame.size.width+wid(20),_label.frame.size.height+wid(10));
    _label.backgroundColor=RBG(100,60,50);
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [UIBezierPath bezierPathWithRoundedRect:_label.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(6, 6)].CGPath;
    _label.layer.mask = shapeLayer;
    
    [self.playBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.equalTo(self.proBGView);
        make.width.height.mas_equalTo(30);
    }];
    
    [self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.playBGView);
        make.width.height.mas_equalTo(18);
    }];
    
    [self.proBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.playBGView.mas_right).offset(10);
        make.right.equalTo(self.contentView).offset(-20);
        make.bottom.mas_equalTo(@-30);
    }];
    [super layoutSubviews];
    self.playerLayer.frame = self.imageView.bounds;
    self.nameClick.frame = self.label.frame;
}
/*
 * 当前播放时间(00:00)
 */
- (NSString *)timeNow {
    
    return [NSString convertStringWithTime:self.playTime.floatValue];
}

/*
 * 总时长(00:00)
 */
- (NSString *)duration {
    
    return [NSString convertStringWithTime:self.playDuration.floatValue];
}

- (void)setModel:(HomeBannerModel *)model {
    _model = model;
    

    NSString *imagePath = model.cover_image;
    
    if ([imagePath hasPrefix:@"http"]) {
        if ([imagePath hasSuffix:@"gif"]) {
            [self.imageView sd_internalSetImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:nil options:SDWebImageRefreshCached context:nil setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (image) {
                    [self.imageView setImage:[UIImage sd_imageWithGIFData:imageData]];
                } else if(image){
                    [self.imageView setImage:image];
                }

            } progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                
            } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                
            }];
        } else {
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:nil];
        }
    } else {
        UIImage *image = [UIImage imageNamed:imagePath];
        if (!image) {
            [UIImage imageWithContentsOfFile:imagePath];
        }
        self.imageView.image = image;
    }
    self.imgCornerRadius = 10;
    
    self.playBGView.hidden = model.media_file.length > 0?NO:YES;
    self.proBGView.hidden  = model.media_file.length > 0?NO:YES;
    _label.text = model.rotation_name;
    __weak typeof(self) weakSelf = self;
    
    if ([model.play_type isEqualToString:@"2"]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf createVideoWithModel:model];
            [weakSelf.player play];
            weakSelf.isPlaying = true;
            [weakSelf startTimer];
        });
    } else {
        NSString *url = model.media_file;
        if (![url containsString:@".mp3"]) {
            url = [[MBGeneralManager manager] getDecryptedStringWithEncryptedString:url];
        }
        
        NSURL *playURL;
        if ([self df_isContainChineseWithStr:url]) {
            playURL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        } else {
            playURL = [NSURL URLWithString:url];
        }
        
        
        AVPlayerItem * songItem = [[AVPlayerItem alloc]initWithURL:playURL];
        
        self.playDuration = [NSString stringWithFormat:@"%.2f",CMTimeGetSeconds(songItem.duration)];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @weakify(self)
            [MBPlayerManager manager].currentPlayerHandle = nil;
            [MBPlayerManager manager].currentPlayer = nil;
            [MBPlayerManager manager].currentPlayModel = nil;
        });
    }
    
    
}

- (void)setIsPlaying:(BOOL)isPlaying {
    _isPlaying = isPlaying;
    if (isPlaying == YES) {
        [self.playBtn setImage:[UIImage imageNamed:@"icon_stopImg"] forState:0];
    } else {
        [self.playBtn setImage:[UIImage imageNamed:@"icon_playImg"] forState:0];
    }
}

- (void)createVideoWithModel:(HomeBannerModel *)model  {
    [self clearNotification];
    NSString *url = model.media_file;
    if (![url containsString:@".mp3"]) {
        url = [[MBGeneralManager manager] getDecryptedStringWithEncryptedString:url];
    }
    
    NSURL *playURL;
    if ([self df_isContainChineseWithStr:url]) {
        playURL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    } else {
        playURL = [NSURL URLWithString:url];
    }
    
    
    AVPlayerItem * songItem = [[AVPlayerItem alloc]initWithURL:playURL];
    
    if (self.player == nil) {
        self.player = [[AVPlayer alloc] initWithPlayerItem:songItem];
        self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        self.playerLayer.frame = self.imageView.bounds;
        [self.imageView.layer addSublayer:self.playerLayer];
    }else {
        [self.player replaceCurrentItemWithPlayerItem:songItem];
    }
    
    @weakify(self)
    [MBPlayerManager manager].currentPlayerHandle = ^{
        @strongify(self)
        [self.player pause];
        [self endTimer];
        self.isPlaying = false;
    };
    [MBPlayerManager manager].currentPlayer = self.player;
    [MBPlayerManager manager].currentPlayModel = model;
 
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:songItem];
    
    self.playDuration = [NSString stringWithFormat:@"%.2f",CMTimeGetSeconds(songItem.duration)];
    //更新播放器进度
    __weak typeof(self) weakSelf = self;
    _timeObserve = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds(songItem.duration);
        if (current) {
            weakSelf.progress = current / total;
            weakSelf.playTime = [NSString stringWithFormat:@"%.f",current];
            weakSelf.playDuration = [NSString stringWithFormat:@"%.2f",total];
        }
    }];
    [self refreshProgress];
}

- (void)clearNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.player removeTimeObserver:_timeObserve];
}


- (void)startTimer {
    [self endTimer];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f / 20 target:self selector:@selector(refreshProgress) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)endTimer {
    [_timer invalidate];
    _timer = nil;
}

- (void)playbackFinished:(NSNotification *)nofi {
    self.proBGView.hidden = true;
}


- (BOOL)df_isContainChineseWithStr:(NSString *)str
{
    NSUInteger length = [str length];
    for (NSUInteger i = 0; i < length; i++) {
        NSRange range = NSMakeRange(i, 1);
        NSString *subString = [str substringWithRange:range];
        const char *cString = [subString UTF8String];
        if (strlen(cString) == 3) {
            return YES;
        }
    }
    return NO;
}

- (void)refreshProgress
{
    //显示时间
    self.proBGView.aLabel.text = self.timeNow;
    self.proBGView.bLabel.text = self.duration;
    self.proBGView.slider.minimumValue = 0;
    self.proBGView.slider.maximumValue = self.playDuration.floatValue;

    //进度条
    float progress = self.progress * self.playDuration.floatValue;
    self.proBGView.slider.value = progress;

}

-(UIImageView *)imageView
{
    if(_imageView == nil)
    {
        _imageView = [[UIImageView alloc]init];
    }
    return _imageView;
}
-(UILabel*)label
{
    if(_label==nil)
    {
        _label=[[UILabel alloc]init];
        _label.textColor=[UIColor whiteColor];
        _label.font=[UIFont systemFontOfSize:FontSize(10)];
        _label.textAlignment=NSTextAlignmentCenter;
    }
    return _label;
}
-(UIView*)labelMaskView
{
    if(_labelMaskView==nil)
    {
        _labelMaskView=[[UIView alloc]init];
    }
    return _labelMaskView;
}

- (UIView *)playBGView
{
    if (!_playBGView) {
        _playBGView = [[UIView alloc] init];
        _playBGView.backgroundColor = ColorFromHexAndAlpa(0x000000, 0.5);
        _playBGView.cornerRadius = 15;
        _playBGView.clipsToBounds = YES;
    }
    return _playBGView;
}

- (UIButton *)playBtn
{
    if (!_playBtn) {
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBtn setImage:[UIImage imageNamed:@"icon_playImg"] forState:0];
        _playBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_playBtn addTarget:self action:@selector(playFunc) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playBtn;
}

- (void)playFunc
{
    if (self.player != nil && [MBPlayerManager manager].currentPlayer == self.player) {
        if (self.isPlaying == false) {
            [self.player play];
            self.isPlaying = true;
        }else {
            [self.player pause];
            self.isPlaying = false;
        }
    } else {
        [self createVideoWithModel:self.model];
        [self.player play];
        self.isPlaying = true;
        [self startTimer];
    }
}

- (void)touchClick {
    if(self.model.link.length > 0) {
            NSURL *URL = [NSURL URLWithString:self.model.link];
            [[UIApplication sharedApplication] openURL:URL options:nil completionHandler:nil];
    }
}

- (DCCycleProgressView *)proBGView
{
    if (!_proBGView) {
        _proBGView = [[NSBundle mainBundle] loadNibNamed:@"DCCycleProgressView" owner:self options:nil].lastObject;
        _proBGView.userInteractionEnabled = NO;
    }
    return _proBGView;
}

- (UIButton *)nameClick {
    if(!_nameClick) {
        _nameClick = [[UIButton alloc] init];
        [_nameClick addTarget:self action:@selector(touchClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nameClick;
}

@end
